<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="categoryName"
            placeholder="请输入分类名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="cateOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <!-- 搜索工作栏 -->
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="题目名称" prop="subjectName">
            <el-input
              v-model="queryParams.subjectName"
              placeholder="请输入题目名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 操作工具栏 -->
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['exam:subject-choices:create']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              v-hasPermi="['exam:subject-short-answer:import']"
            >导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              :loading="exportLoading"
              v-hasPermi="['exam:subject-short-answer:export']"
            >导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <!-- 列表 -->
        <el-table v-loading="loading" :data="list">
          <el-table-column
            label="题目名称"
            align="center"
            prop="subjectName"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">{{resHtml(scope.row.subjectName)}}</template>
          </el-table-column>
          <el-table-column label="分值" align="center" prop="score" width="50"/>
          <el-table-column label="参考答案" align="center" prop="answer" :show-overflow-tooltip="true"/>
          <el-table-column label="难度等级" align="center" prop="level">
            <template slot-scope="scope">
              <el-rate :value="scope.row.level" disabled></el-rate>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" width="150">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['exam:subject-choices:update']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['exam:subject-choices:delete']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNo"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
      v-if="open"
    >
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="单选题" name="0">
          <choices ref="choices" :subject="tempSubject"/>
        </el-tab-pane>
        <el-tab-pane label="多选题" name="3">
          <MultipleChoices ref="multipleChoices" :subject="tempSubject"/>
        </el-tab-pane>
        <el-tab-pane label="判断题" name="2">
          <Judgement ref="judgement" :subject="tempSubject"/>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :data="uploadData"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip text-center" slot="tip">
          <!-- <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>-->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate"
          >下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  createSubjectChoices,
  updateSubjectChoices,
  deleteSubjectChoices,
  getSubject,
  getSubjectChoicesPage,
  exportSubject,
  importTemplate
} from "@/api/exam/subjectChoices";
import { getSimpleList } from "@/api/examination/subjectCategory";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import tinymce from "@/components/tinymce";
import Choices from "@/components/Subjects/Choices";
import MultipleChoices from "@/components/Subjects/MultipleChoices";
import Judgement from "@/components/Subjects/Judgement";
import { getBaseHeader } from "@/utils/request";
export default {
  name: "SubjectChoices",
  components: {
    Treeselect,
    tinymce,
    Choices,
    MultipleChoices,
    Judgement
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 选择题列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: getBaseHeader(),
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/admin-api/exam/subject/import"
      },
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        subjectName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // subjectName: [{ required: true, message: "题目名称不能为空", trigger: "blur" }],
        // choicesType: [{ required: true, message: "题目类型不能为空", trigger: "change" }],
        // answer: [{ required: true, message: "参考答案不能为空", trigger: "blur" }],
        // score: [{ required: true, message: "题目分值不能为空", trigger: "blur" }],
        // level: [{ required: true, message: "难度等级不能为空", trigger: "blur" }],
        // applicationCode: [{ required: true, message: "系统编号不能为空", trigger: "blur" }],
      },

      defaultProps: {
        children: "children",
        label: "categoryName"
      },
      cateOptions: [],
      categoryName: undefined,
      choicesType: undefined,
      //默认标签页
      activeName: 0,
      // 题目临时信息
      tempSubject: {
        id: "",
        examinationId: undefined,
        categoryId: undefined,
        subjectName: null,
        type: 0,
        choicesType: 0,
        options: [
          { subjectChoicesId: "", optionName: "A", optionContent: "" },
          { subjectChoicesId: "", optionName: "B", optionContent: "" },
          { subjectChoicesId: "", optionName: "C", optionContent: "" },
          { subjectChoicesId: "", optionName: "D", optionContent: "" }
        ],
        answer: {
          subjectId: "",
          answer: "",
          answerType: "",
          score: ""
        },
        score: 5,
        analysis: null,
        level: 2,
        status: 0
      },
      // 0：试卷的题目，1：题库的题目
      subjectsType: "0",
      uploadData: {
        deptId: this.$store.getters.deptId
      }
    };
  },
  watch: {
    // 根据名称筛选分类
    categoryName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getTreeselect();
    let subjectInfo = [];
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getSubjectChoicesPage(this.queryParams).then(response => {
        this.list = response.data.list;
        this.total = parseInt(response.data.total);
        this.loading = false;
      });
    },
    resHtml(item) {
      return item.replace(/<[^>]+>/g, ""); // 去掉所有的html标记
    },
    /** 查询分类下拉树结构 */
    getTreeselect() {
      getSimpleList().then(response => {
        for (let i = 0; i < response.data.length; i++) {
          response.data[i].id = parseInt(response.data[i].id);
          response.data[i].parentId = parseInt(response.data[i].parentId);
          response.data[i].categoryName =
            response.data[i].categoryName + "  - 类目ID:" + response.data[i].id;
        }
        // 处理 deptOptions 参数
        this.cateOptions.push(...this.handleTree(response.data, "id"));
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.categoryName.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.categoryId = data.id;
      this.getList();
    },

    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      (this.tempSubject = {
        id: null,
        categoryId: undefined,
        subjectName: null,
        type: 0,
        choicesType: 0,
        options: [
          { subjectChoicesId: "", optionName: "A", optionContent: "" },
          { subjectChoicesId: "", optionName: "B", optionContent: "" },
          { subjectChoicesId: "", optionName: "C", optionContent: "" },
          { subjectChoicesId: "", optionName: "D", optionContent: "" }
        ],
        answer: {
          subjectId: "",
          answer: "",
          answerType: "",
          score: ""
        },
        score: 5,
        analysis: null,
        level: 2,
        status: 0
      }),
        this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();

      this.tempSubject.categoryId = this.queryParams.categoryId;
      console.log(this.tempSubject);
      this.updateComponentSubjectInfo();
      this.open = true;
      this.title = "添加单选题";
      setTimeout(() => {
        const ref = this.getSubjectRef();
        this.$nextTick(ref.initDefaultOptions());
        // if (isNotEmpty(ref)) {
        //   this.$nextTick(() => {
        //     // 初始化单选题选项
        //     ref.initDefaultOptions()
        //   })
        // }
      }, 200);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      const type = 0;
      getSubject(id, type).then(response => {
        this.tempSubject = response.data;

        // console.log( this.tempSubject)
        this.activeName = this.tempSubject.choicesType;
        this.updateComponentSubjectInfo();
        this.open = true;
        this.title = "修改选择题";
        setTimeout(() => {
          const ref = this.getSubjectRef();
          this.$nextTick(ref.setSubjectInfo(this.tempSubject));
        }, 200);
      });
    },
    /** 提交按钮 */
    submitForm() {
      const ref = this.getSubjectRef();
      if (ref.validate()) {
        let subjectInfo = ref.getSubjectInfo();
        subjectInfo.deptId = this.$store.getters.deptId;
        // 修改的提交

        if (subjectInfo.id != null && subjectInfo.id > 0) {
          updateSubjectChoices(subjectInfo).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createSubjectChoices(subjectInfo).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal
        .confirm('是否确认删除选择题编号为"' + id + '"的数据项?')
        .then(function() {
          return deleteSubjectChoices(id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = { ...this.queryParams };
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal
        .confirm("是否确认导出所有试题?")
        .then(() => {
          this.exportLoading = true;
          return exportSubject(params);
        })
        .then(response => {
          this.$download.excel(response, "试题.xls");
          this.exportLoading = false;
        })
        .catch(() => {});
    },
    // 格式化课程树的下拉框
    normalizer(node) {
      return {
        id: node.id,
        label: node.categoryName,
        children: node.children
      };
    },
    //标签页切换
    handleClick(tab, event) {
      this.title = "添加" + tab.label;
      //this.tempSubject.type = parseInt(tab.name)
      this.tempSubject.choicesType = parseInt(tab.name);
      this.tempSubject.type = parseInt(tab.name);
      // 更新组件里的题目信息
      this.updateComponentSubjectInfo();
    },
    resetTempSubject(score) {
      this.tempSubject = {
        id: "",
        examinationId: undefined,
        categoryId: undefined,
        subjectName: "",
        type: 0,
        choicesType: 0,
        options: [
          { subjectChoicesId: "", optionName: "A", optionContent: "" },
          { subjectChoicesId: "", optionName: "B", optionContent: "" },
          { subjectChoicesId: "", optionName: "C", optionContent: "" },
          { subjectChoicesId: "", optionName: "D", optionContent: "" }
        ],
        answer: {
          subjectId: "",
          answer: "",
          answerType: "",
          score: ""
        },
        score: score,
        analysis: "",
        level: 2
      };
      this.$refs["choices"].resetTempSubject(score);
      this.$refs["multipleChoices"].resetTempSubject(score);
      this.$refs["judgement"].resetTempSubject(score);
    },
    //切换题型
    getSubjectRef() {
      let ref;
      this.activeName = this.activeName.toString();
      switch (this.activeName) {
        case "0":
          ref = this.$refs.choices;
          break;
        case "3":
          ref = this.$refs["multipleChoices"];
          break;
        case "2":
          ref = this.$refs["judgement"];
          break;
      }
      return ref;
    },
    // 更新组件里的题目信息
    updateComponentSubjectInfo() {
      // 单选题
      const ref = this.getSubjectRef();
      if (ref != "" && ref != undefined) {
        console.log("更新temsubject");
        ref.setSubjectInfo(this.tempSubject);
      }
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.$download.excel(response, "试题导入模板.xls");
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      if (response.code !== 0) {
        this.$modal.msgError(response.msg);
        return;
      }
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      // 拼接提示语
      let data = response.data;
      let text = "导入成功";
      if (data.createSubjectName && data.createSubjectName.length > 0) {
        text += "&nbsp;:" + data.createSubjectName.length + "条";
      }

      this.$alert(text, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
